package com.xw.controller;


import com.github.pagehelper.PageInfo;
import com.xw.common.Constants;
import com.xw.common.Result;
import com.xw.dao.RolesDao;
import com.xw.dao.UserDao;
import com.xw.entity.Roles;
import com.xw.entity.User;
import com.xw.rep.RoleByMenuRep;
import com.xw.req.AddRoleMenuReq;
import com.xw.req.PageRequest;
import com.xw.service.RolesService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
/**
 * @Description: TODO
 * @Date: 2024/12/18 16:52
 * @Version: 1.0
 * @author 86151
 */
@RestController
@RequestMapping("role")
@Api(tags = "角色模块")
public class RoleController {

    @Resource
    private RolesDao rolesDao;

    @Resource
    private UserDao userDao;

    @Resource
    private RolesService rolesService;

    @PostMapping("page")
    @ApiOperation(value = "角色列表")
    public Result<?> page(@RequestBody PageRequest<Roles> pageRequest) {
        PageInfo<Roles> rolesPageInfo = rolesService.queryByPage(pageRequest);
        return new Result<>(rolesPageInfo, Constants.SUCCESS);
    }

    @PostMapping("saveOrUpdate")
    @ApiOperation(value = "角色的新增或修改")
    public Result<?> saveOrUpdate(@RequestBody @Validated Roles roles) {
        if (roles.getId() == null) {
            rolesDao.insert(roles);
        } else {
            rolesDao.update(roles);
        }
        return new Result<>(Constants.SUCCESS);
    }


    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除数据(ID)")
    public Result<?> delete(@PathVariable("id") Integer id) {
        Roles roleToDelete = rolesDao.queryById(id);
        if (roleToDelete == null) {
            return new Result<>("角色不存在", Constants.ERROR);
        }
        // 判断是否为默认角色（ROLE_USER），如果是则提示不能删除
        if ("ROLE_USER".equals(roleToDelete.getName())) {
            return new Result<>("默认角色不能删除，请重新选择要删除的角色", Constants.ERROR);
        }
        // 假设userDao是已注入的UserDao实例，用于查询关联用户
        List<User> usersWithThisRole = userDao.findUsersByRole(roleToDelete.getName());
        if (!usersWithThisRole.isEmpty()) {
            // 遍历关联用户，将其角色修改为默认角色（ROLE_USER）
            for (User user : usersWithThisRole) {
                user.setRole("ROLE_USER");
                userDao.updateById(user);
            }
        }
        rolesDao.deleteById(id);
        return new Result<>(Constants.SUCCESS);
    }
    @PostMapping("deleteByIds")
    @ApiOperation(value = "批量删除角色")
    public Result<?> deleteByIds(@RequestBody List<Integer> ids) {
        rolesDao.deleteBatchByIds(ids);
        return new Result<>(Constants.SUCCESS);
    }

    @GetMapping("selectAll")
   @ApiOperation(value = "查询所有角色信息")
    public Result<?> selectAll() {
     return new Result<>(rolesDao.queryAll(),Constants.SUCCESS);
  }

    @GetMapping("selectRoleByMenu")
    @ApiOperation(value = "查询角色下的菜单")
    public Result<?> selectRoleByMenu(@RequestParam Integer roleId) {
        RoleByMenuRep roleByMenuRep = rolesService.selectRoleByMenu(roleId);
        return new Result<>(roleByMenuRep,Constants.SUCCESS);
    }

    @PostMapping("addRoleMenu")
    @ApiOperation(value = "新增角色菜单")
    public Result<?> addRoleMenu(@RequestBody @Validated AddRoleMenuReq addRoleMenuReq) {
        rolesService.addRoleMenu(addRoleMenuReq);
        return new Result<>(Constants.SUCCESS);
    }
}
